﻿using Dyao.Book.Contract;
using Dyao.Book.Core;
using Foundation.Core;
using Foundation.IdCreate;
using Foundation.Spider.Selector;
using Microsoft.Extensions.Logging;

namespace Dyao.Book.Application
{
    public class HtmlContentParsePlugins : IBusinessPlugin<BookContentParsePluginsContext>, ITransientDependency
    {
        public readonly IIdCreater _idCreater;

        public readonly ILogger<HtmlContentParsePlugins> _logger;

        public HtmlContentParsePlugins(IIdCreater idCreater,
            ILogger<HtmlContentParsePlugins> logger)
        {
            _idCreater = idCreater;
            _logger = logger;
        }

        public async Task ExecuteAsync(BookContentParsePluginsContext executeContext, Func<BookContentParsePluginsContext, CancellationToken, Task> next, CancellationToken cancellationToken)
        {
            await _logger.LogConsumeTimeAsync(async () =>
            {
                var result = await Parse(executeContext);

                if (!result.IsNullOrEmpty())
                    executeContext.Output = result;

                await next(executeContext, cancellationToken);

            }, "ExecuteAsync");
        }

        public async Task<List<ChapterContentParseDto>> Parse(BookContentParsePluginsContext executeContext)
        {
            var bookCatalogues = new List<ChapterContentParseDto>();
            var context = executeContext.Input;
            var ruleProp = executeContext.Args.SpiderRule;
            var contentProp = executeContext.Args.Chapter;

            try
            {
                // 网页数据解析
                var masterNode = context.Selectable.Select(Selectors.XPath(ruleProp.ContentList));
                var itemNodes = masterNode.SelectList(Selectors.XPath(ruleProp.ContentItem));
                int rid = 0;

                foreach (var p in itemNodes)
                {
                    var code = await _idCreater.CreateAsync(IdBusinessType.BookChapterContentRedisId, null, default);
                    rid++;
                    var content = p.Value?.Trim();
                    bookCatalogues.Add(new ChapterContentParseDto()
                    {
                        ID = code.ToString(),
                        BookCatalogueId = contentProp.BookCatalogueId,
                        WordsNumber = content.Length,
                        Seq = rid,
                        Content = content,
                    });
                }

                if (bookCatalogues.Count() <= 10)
                    bookCatalogues.Clear();

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }

            return bookCatalogues;
        }
    }
}
